package net.dgg.zz.api.production.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.zz.api.production.dto.ScOrderAndTaskDTO;
import net.dgg.zz.api.production.dto.TaskListVo;
import net.dgg.zz.api.production.dto.TaskOperateRecordDTO;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.constant.SystemCommonConstant;
import net.dgg.zz.common.entity.PageList;
import net.dgg.zz.common.entity.TaskOperateRecord;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.files.entity.Annex;
import net.dgg.zz.common.files.service.AnnexService;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.systemRecord.dao.SystemRecordDao;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.inProcess.dao.ProductNodeOperatingDao;
import net.dgg.zz.production.inProcess.dao.ProductOrderDao;
import net.dgg.zz.production.inProcess.dao.ProductTimeStatusDao;
import net.dgg.zz.production.inProcess.entity.ProductNodeOperating;
import org.noka.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>@Title 生产部分对外接口service</p>
 * <p>@Description 办理中Service</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author maoquanyi</p>
 * <p>@date 2018年08月13日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Service
public class ApiProductionService extends BaseService {

    //新的引入
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Autowired
    private ProductNodeOperatingDao productNodeOperatingDao;
    @Resource
    private SystemRecordDao systemRecordDao;
    @Resource
    private CommonMangerExtService  commonMangerExtService;
    @Resource
    private DateUtils dateUtils;//日期
    @Autowired
    private AnnexService annexService;

    /**
    * <p>@Description 统计生产订单相关</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/6 0006 9:48 创建时间</p>
    * <p>@return</p>
    */
    public Integer productOrderCount(Map map){
        return productOrderDao.productionOrderCount(map);
    }
    /**
     * <p>@Description 统计各种类型的操作记录数量</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/6 0006 11:22 创建时间</p>
     * <p>@return</p>
     */
    public Integer productSystemCount(Map params){
        return systemRecordDao.productSystemCount(params);
    }

    /**
     * <p>@Description 统计完结相关</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/6 0006 9:48 创建时间</p>
     * <p>@return</p>
     */
    public Integer productOperatingCount(Map map){
        return productNodeOperatingDao.productOperatingCount(map);
    }

    /**
     * <p>@Description 统计完结相关</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/6 0006 9:48 创建时间</p>
     * <p>@return</p>
     */
    public Integer productTimeStatusCount(Map map){
        return productTimeStatusDao.productTimeStatusCount(map);
    }

    /**
    * <p>@Description 接口专用: 根据销售订单ID查询所有生产订单信息</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/19 0019 14:16 创建时间</p>
    * <p>@return</p>
    */
    //[{orderNo=D2018091800739,
    // productId=7730329839738617856,
    // orderId=7730329099833761792,
    // completedTime=2018-09-18 18:04:33,
    // scOrderNo=M2018091800627,
    // scProductOrderNo=SC2018091801026,
    // productName=认缴注册（测试）,
    // productAttr=,
    // receiveTime=2018-09-18 18:02:42,
    // useTime=0,
    // id=7730331830434988032,
    // productGoodsId=,
    // status=SC_GSSC_STATE_SCPROORDER_CODE11}]

    public String queryProductOrderByOrderId(Long orderId){
        ValidateUtils.strNotEmpty(orderId,CommonExcption.class,"销售订单ID不能为空!");
        List<Map> mapList = productOrderDao.queryProductOrderByOrderId(new HashMap() {{
            put("orderId", orderId);
        }});
        String data = JsonUtil.obj2Json(mapList);

        return data;
    }


    /**
     * @Title:
     * @Description: 会员中心通过销售订单ID获取生产订单最新节点信息
     * @param:
     * @return:
     * @throw:
     * @author: wmj
     * @creat_date: 2019/2/23
     **/
    public Map getScOrderLatestNodeByOrderId(Map<String, Object> params) {
        Map map = new HashMap();
        ProductOrder gsscProductOrder = productOrderDao.queryLatestScOrder(params);
        map.put("productName", gsscProductOrder == null ? "" : gsscProductOrder.getProductName() == null ? "" : gsscProductOrder.getProductName());
        map.put("latestNode", gsscProductOrder == null ? "" : gsscProductOrder.getLatestEndNodeName() == null ? "" : gsscProductOrder.getLatestEndNodeName());
        return map;
    }

    /**
     * @Title:
     * @Description: 会员中心通过销售订单ID获取生产订单业务办理进度
     * @param:
     * @return:
     * @throw:
     * @author: wmj
     * @creat_date: 2019/2/23
     **/
    public List<List<Map<String, Object>>> queryBusProgress(Long orderId) {
        List<ProductOrder> scOrderList = productOrderDao.queryAllScorder(orderId);
        List<List<Map<String, Object>>> allBusinessList = new ArrayList<>();

        for (ProductOrder productOrder: scOrderList) {
            List<Map<String, Object>> businessList = new ArrayList<>();
            Map map = new HashMap();
            List<LinkedHashMap> newprogressList = new ArrayList<>();
            Long scOrderId = productOrder.getId();
            Map<String, Object> params = new HashMap<>();
            params.put("scorderId", scOrderId);
            /*单个查询生产订单基本信息*/
            Long flowUserId = productOrder.getFlowUserId();
            if (flowUserId != null) {
                Map userMap = commonMangerExtService.searchUserById(flowUserId);
                /*查询订单历史更新节点记录信息*/
                List<LinkedHashMap> progressList = productOrderDao.queryBusinessProgress(params);
                /*为每个节点记录注入流程人员信息，本应该取记录创建者去循环获取用户信息，因考虑查询效率问题改为获取当前订单的流程人员放置到每个节点上*/
                for (LinkedHashMap nodeMap : progressList) {
                    nodeMap.put("nodeOrgName", String.valueOf(userMap.get("orgName")));
                    nodeMap.put("nodeUserName", String.valueOf(userMap.get("realName")));
                    nodeMap.put("nodePhone", String.valueOf(userMap.get("phone")));
                    newprogressList.add(nodeMap);
                }
                /*给list注入当前节点信息*/
                /*if (!StringUtils.isEmpty(productOrder.getLatestEndNodeName())) {
                    LinkedHashMap nowNodeMap = new LinkedHashMap();
                    nowNodeMap.put("nodeName", productOrder.getLatestEndNodeName());
                    nowNodeMap.put("progress", "OVERDUE_STATE0");
                    nowNodeMap.put("nodeOverdueTime", null);
                    nowNodeMap.put("createTime", null);
                    nowNodeMap.put("nodeOrgName", String.valueOf(userMap.get("orgName")));
                    nowNodeMap.put("nodeUserName", String.valueOf(userMap.get("realName")));
                    nowNodeMap.put("nodePhone", String.valueOf(userMap.get("phone")));
                    newprogressList.add(nowNodeMap);
                }*/
            }
            map.put("progressList", newprogressList);
            map.put("productName",productOrder.getProductName());

            businessList.add(map);
            allBusinessList.add(businessList);
        }

        return allBusinessList;
    }
    /**
     * @Title:
     * @Description: TODO 根据销售订单ID查询所有生产订单信息
     * @param:
     * @return:
     * @throw:
     * @author: sdx
     * @creat_date: 2019/8/26
     **/
    public List<Map<String, Object>> getZzProductOrderByOrderId(Map<String, Object> params) {
        List<Map<String, Object>> list = new ArrayList<>();
        list = productOrderDao.getZzProductOrderByOrderId(params);
        return list;
    }
    /**
     * 获取当前生产订单节点操作记录
     * @param params
     * @return
     */
    public List<Map<String, Object>> getProductOrderById(Map<String, Object> params) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<ProductNodeOperating> nodeList = productOrderDao.getProductOrderById(params);
        if(!CollectionUtils.isEmpty(nodeList)){
            for(ProductNodeOperating node :nodeList){
                Map<String, Object> map = new HashMap();
                map.put("nodeName",node.getNodeName());
                map.put("handlerName",node.getFlowUserName());
                map.put("latestOperateTime",node.getNodeOpetateTime());
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 获取当前生产订单节点操作记录
     * @param params
     * @return
     */
    public List<TaskOperateRecord> getProductNodeById(Map<String, Object> params) {
        List<TaskOperateRecord> list = new ArrayList<>();
        List<ProductNodeOperating> nodeList = productOrderDao.getProductNodeById(params);
        if(!CollectionUtils.isEmpty(nodeList)){
            for(ProductNodeOperating node :nodeList){
                TaskOperateRecord taskOperateRecord = new TaskOperateRecord();
                taskOperateRecord.setScOrderId(String.valueOf(node.getScProductOrderId()));
                taskOperateRecord.setTaskId(String.valueOf(node.getNodeId()));
                taskOperateRecord.setNodeId(String.valueOf(node.getNodeId()));
                taskOperateRecord.setNodeName(node.getNodeName());
                taskOperateRecord.setTaskName(node.getNodeName());
                taskOperateRecord.setOperateTime(node.getNodeOpetateTime());
                taskOperateRecord.setOperaterName(node.getFlowUserName());
                taskOperateRecord.setRemarks(node.getRemark());
                list.add(taskOperateRecord);
            }
        }
        return list;
    }

    public Integer count(Map<String, Object> params) {
        List<ProductNodeOperating> nodeList = productOrderDao.getProductOrderById(params);
        return nodeList.size();
    }

    /**
     * 通过生产单id集合查询生产单信息
     * @param scOrderIds
     * @return
     */
    public List<ScOrderAndTaskDTO> getScOrderAndTask(List<Long> scOrderIds, Integer start, Integer limit) {
        List<ScOrderAndTaskDTO> scOrderAndTaskDTOS = new ArrayList<>();
        List<Map<String,Object>> productOrderMaps = productOrderDao.getScOrderAndTask(scOrderIds);
        for(Map<String,Object> orderMap : productOrderMaps){
            //封装生产单信息
            ScOrderAndTaskDTO scOrderAndTaskDTO = new ScOrderAndTaskDTO();
            scOrderAndTaskDTO.setScOrderId(Long.valueOf(String.valueOf(orderMap.get("scOrderId"))));
            scOrderAndTaskDTO.setScOrderNo(String.valueOf(orderMap.get("scOrderNo")));
            Date startDate = DateUtil.stringDateToDate(String.valueOf(orderMap.get("startTime")));
            //节点数据
            JSONObject json = JSONObject.parseObject(String.valueOf(orderMap.get("flowContent")));
            Boolean isOld = true;
            if(json.containsKey("data")){
                isOld = false;
                json = json.getJSONObject("data");
            }
            Integer day = json.getInteger("processingCycle");
            scOrderAndTaskDTO.setStartTime(startDate);
            //计算到期时间   1:工作日；2：自然日
            Date endDate = null;
            //工作日还自然日为空就跳过计算
            Integer currentNodeIsNaturalorWorkday = json.getInteger("cycleType");
            if (currentNodeIsNaturalorWorkday != null && StringUtils.isNotEmpty(startDate)) {
                //计算到期时间
                if (currentNodeIsNaturalorWorkday == 1) {
                    endDate = dateUtils.getWorkDateFrom(startDate, day);
                } else if (currentNodeIsNaturalorWorkday == 2){
                    endDate = dateUtils.getDateFrom(startDate, day);
                }
            }
            scOrderAndTaskDTO.setDeadLine(endDate);
            if(StringUtils.isNotEmpty(endDate)){
                if(ScProductConstant.SC_ORDER_JUNCTIONS.equals(String.valueOf(orderMap.get("status")))){
                    Date completionDate = DateUtil.stringDateToDate(String.valueOf(orderMap.get("completedTime")));
                    if(completionDate.getTime()>endDate.getTime()){
                        scOrderAndTaskDTO.setIsOverdue("0");
                        scOrderAndTaskDTO.setTaskOverTime(String.valueOf(completionDate.getTime()-endDate.getTime()));
                    }else {
                        scOrderAndTaskDTO.setIsOverdue("1");
                    }
                }else {
                    if(System.currentTimeMillis()>endDate.getTime()){
                        scOrderAndTaskDTO.setIsOverdue("0");
                        scOrderAndTaskDTO.setTaskOverTime(String.valueOf(System.currentTimeMillis()-endDate.getTime()));
                    }else {
                        scOrderAndTaskDTO.setIsOverdue("1");
                    }
                }
            }
            JSONArray nodes = json.getJSONArray("nodeDtoList");
            //封装节点信息
            PageList<TaskListVo> taskListVos = new PageList<>();
            List<TaskListVo> taskListVoList = new ArrayList<>();
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                TaskListVo taskListVo = new TaskListVo();
                if(isOld){
                    taskListVo.setTaskName(node.getString("taskName"));
                    taskListVo.setIsKeyTask(node.getString("isKeyTask"));
                }else {
                    taskListVo.setTaskName(node.getString("name"));
                    taskListVo.setIsKeyTask(node.getString("isKey"));
                }
                taskListVo.setTaskId(node.getString("id"));
                if(node.containsKey("brokerage")){
                    taskListVo.setBrokerage(node.getBigDecimal("brokerage"));
                }else {
                    taskListVo.setBrokerage(new BigDecimal(0.00));
                }
                taskListVo.setProductName(orderMap.get("productName").toString());
                Integer nodeCount = productOrderDao.getIsTaskSwitching(taskListVo.getTaskId(), String.valueOf( scOrderAndTaskDTO.getScOrderId()));
                if(StringUtils.isNotEmpty(nodeCount) && nodeCount > 0){
                    taskListVo.setTaskSwitching("1");
                }else {
                    taskListVo.setTaskSwitching("0");
                }
                taskListVoList.add(taskListVo);
            }
            //获取fileId
            String fileId = null;
            if (StringUtils.isNotEmpty(orderMap.get("scOrderId").toString())) {
                fileId = orderMap.get("scOrderId").toString();
                fileId = SystemCommonConstant.ANNEX_FILE_ID_PREFIX + "_" + fileId + "_" + SystemCommonConstant.ANNEX_PRODUCT_PREFIX;// 附件id命名规则：系统_数据Id_模块
                scOrderAndTaskDTO.setFileId(fileId);
            }else {
                scOrderAndTaskDTO.setFileId("");
            }

            taskListVos.setCurrentPage(start);
            taskListVos.setPageSize(limit);
            taskListVos.setTotalCount(taskListVoList.size());
            taskListVos.setRecords(taskListVoList);
            scOrderAndTaskDTO.setTaskListVos(taskListVos);
            scOrderAndTaskDTOS.add(scOrderAndTaskDTO);
        }
        return scOrderAndTaskDTOS;
    }

    /**
     * 通过任务ID查询任务操作记录
     * @param taskId
     * @return
     */
    public PageList<TaskOperateRecordDTO> getNodeRecords(String taskId, String scOrderId, Integer start, Integer limit) {
        PageList<TaskOperateRecordDTO> taskOperateRecordDTOPageList = new PageList<>();
        List<TaskOperateRecordDTO> taskOperateRecordDTOS = new ArrayList<>();
        List<Map<String,Object>> nodes = productOrderDao.getNodeRecords(taskId, scOrderId, (start-1)*limit,limit);
        //封装节点操作记录信息
        for(Map<String,Object> node : nodes){
            TaskOperateRecordDTO taskOperateRecordDTO = new TaskOperateRecordDTO();
            taskOperateRecordDTO.setNodeId(String.valueOf(node.get("nodeId")));
            taskOperateRecordDTO.setTaskId(String.valueOf(node.get("nodeId")));
            taskOperateRecordDTO.setNodeName(String.valueOf(node.get("nodeName")));
            taskOperateRecordDTO.setTaskName(String.valueOf(node.get("nodeName")));
            taskOperateRecordDTO.setOperateName(String.valueOf(node.get("flowUserName")));
            taskOperateRecordDTO.setOperateTime(DateUtil.stringDateToDate(String.valueOf(node.get("createTime"))));
            taskOperateRecordDTO.setScOrderId(String.valueOf(node.get("scOrderId")));
            taskOperateRecordDTO.setRemarks(StringUtils.isNotEmpty(node.get("remarks")) ? String.valueOf(node.get("remarks")):"");
            Integer type = Integer.valueOf(String.valueOf(node.get("remarksType")));
            if(type == 1){
                taskOperateRecordDTO.setOperateType("节点更新");
            }
            if(type == 2){
                taskOperateRecordDTO.setOperateType("备注");
            }
            taskOperateRecordDTOS.add(taskOperateRecordDTO);
        }
        taskOperateRecordDTOPageList.setCurrentPage(start);
        taskOperateRecordDTOPageList.setPageSize(limit);
        taskOperateRecordDTOPageList.setTotalCount(productOrderDao.getNodeRecordsTatolCount(taskId,scOrderId));
        taskOperateRecordDTOPageList.setRecords(taskOperateRecordDTOS);
        return taskOperateRecordDTOPageList;
    }
}
